<template>
  <div class="org-container">
    <!-- 新增加载遮罩层 -->
    <div class="global-loading-overlay" v-if="isConfirming">
      <van-loading type="spinner" color="#1989fa" size="24px" />
    </div>

    <!-- 顶部导航栏 -->
    <div class="nav-bar">
      <div class="nav-left">
        <van-icon
          name="arrow-left"
          class="back-icon"
          @click="handleBack"
          v-if="!isRootLevel"
        />
        <span>{{
          isRootLevel ? "组织架构" : `返回上级(${currentParent?.label})`
        }}</span>
      </div>
      <div
        v-show="!searchText"
        class="all-selection"
        @click.stop="handleAllNodeSelection()"
      >
        {{ isAllChecked ? "取消全选" : "全选" }}
      </div>
    </div>

    <!-- 固定搜索框 -->
    <div class="search-bar">
      <van-search
        v-model="searchText"
        placeholder="搜索成员或部门"
        shape="round"
        @search="handleSearch"
        @clear="handleClearSearch"
      />
    </div>

    <!-- 可滚动内容区域 -->
    <div class="scroll-content">
      <transition name="fade">
        <div v-if="!currentChildren" class="list-container">
          <div v-for="item in filteredList" :key="item.id" class="row">
            <!-- 部门行 -->
            <div
              v-if="
                item.type === 'department' ||
                (item.children && item.children.length > 0)
              "
              class="row-department"
              @click.stop="showChildren(item)"
            >
              <div class="selection-container">
                <div
                  class="selection-checkbox department-checkbox"
                  :class="{
                    checked: item.checkedStatus === 'checked',
                    indeterminate: item.checkedStatus === 'indeterminate',
                  }"
                  @click.stop="handleToggleNodeSelection(item)"
                >
                  <span v-if="item.checkedStatus === 'checked'" class="icon"
                    >✓</span
                  >
                  <span
                    v-else-if="item.checkedStatus === 'indeterminate'"
                    class="icon"
                    >-</span
                  >
                </div>
              </div>
              <div class="content">
                <van-icon name="wap-home" />
                <span class="name">{{ item.label }}</span>
              </div>
              <div v-if="item.children && item.children.length > 0">
                <van-icon name="arrow" class="arrow-icon" />
              </div>
            </div>

            <!-- 成员行 -->
            <div v-else class="row-member">
              <div class="selection-container">
                <div
                  class="selection-checkbox member-checkbox"
                  :class="{ checked: item.checkedStatus === 'checked' }"
                  @click.stop="handleToggleNodeSelection(item)"
                >
                  <span v-if="item.checkedStatus === 'checked'" class="icon"
                    >✓</span
                  >
                </div>
              </div>
              <div class="content">
                <van-icon name="user" color="#409eff" />
                <span class="name">{{ item.label }}</span>
              </div>
            </div>
          </div>
        </div>
      </transition>

      <!-- 子层级 -->
      <transition name="slide-left">
        <div v-if="currentChildren" class="child-view">
          <Org
            :treeData="currentChildren"
            :parentNode="currentParent"
            @change="handleChildrenChange"
          />
        </div>
      </transition>
    </div>

    <!-- 底部选中栏 -->
    <div v-show="checkedNodes.length > 0" class="selection-bar">
      <div class="selected-header">
        <span>已选 {{ checkedNodes.length }} 项</span>
        <van-button
          size="mini"
          type="primary"
          plain
          @click="clearAllSelected"
          v-if="checkedNodes.length > 0"
        >
          清空
        </van-button>
      </div>
      <div class="selected-items-wrapper">
        <div class="selected-items">
          <van-tag
            v-for="item in checkedNodes"
            :key="item.id"
            type="primary"
            size="medium"
            closeable
            @close="removeSelected(item)"
          >
            {{ item.label }}
          </van-tag>
        </div>
      </div>
    </div>

    <!-- 底部固定按钮 -->
    <div class="confirm-button-container">
      <van-button type="primary" block @click="handleConfirm">
        确定
      </van-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "Org",
  components: {},
  props: {
    treeData: {
      type: Array,
      default: () => [],
      required: true,
    },
    parentNode: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      currentChildren: null,
      currentParent: null,
      localOrgList: [],
      searchText: "",
      isConfirming: false,
    };
  },
  computed: {
    ...mapState({
      orginTreeData: (state) => state.orgTree.orginTreeData,
      flatTreeData: (state) => state.orgTree.flatTreeData,
      checkedNodes: (state) => state.orgTree.checkedNodes,
    }),
    isAllChecked() {
      return this.localOrgList.every((item) => {
        return item.checkedStatus === "checked";
      });
    },
    isRootLevel() {
      return this.parentNode === null;
    },
    filteredList() {
      if (!this.searchText) return this.localOrgList;
      const search = this.searchText.toLowerCase();

      const list = this.flatTreeData.filter(
        (item) =>
          item.label.toLowerCase().includes(search) && item.type === "person"
      );
      return list.slice(0, 10);
    },
  },
  watch: {
    treeData: {
      deep: true,
      handler() {
        this.initLocalData();

        // console.log(
        //   `子组件监听到父组件数据变化${this.treeData[0].level}`,
        //   this.localOrgList
        // );
        if (this.currentChildren && this.currentChildren.length > 0) {
          const currentParentId = this.currentChildren[0].parentId;
          const item = this.localOrgList.find(
            (item) => item.id === currentParentId
          );
          this.currentParent = item;
          this.currentChildren = item.children;
        }
      },
    },
    checkedNodes: {
      handler() {
        this.scrollToRight();
      },
      deep: true,
    },
  },
  created() {
    this.initLocalData();
    this.currentParent = this.parentNode;
  },
  methods: {
    initLocalData() {
      this.localOrgList = JSON.parse(JSON.stringify(this.treeData));
    },

    showChildren(item) {
      this.currentChildren = item.children;
      this.currentParent = item;
    },

    handleBack() {
      this.$parent.currentChildren = null;
      this.$parent.currentParent = this.$parent.parentNode;
    },

    handleSearch() {
      console.log("搜索:", this.searchText);
    },

    handleClearSearch() {
      this.searchText = "";
    },

    removeSelected(item) {
      // this.$store.dispatch("orgTree/removeNode", item);
      this.handleToggleNodeSelection(item, true);
    },

    clearAllSelected() {
      this.$store.dispatch("orgTree/clearOrgTreeCheckedStatus");
    },

    handleUpdateCheckedNodes(node) {
      if (node.type === "person") {
        if (node.checkedStatus === "checked") {
          this.$store.dispatch("orgTree/addNode", node);
        } else {
          this.$store.dispatch("orgTree/removeNode", node);
        }
        // 更新扁平化数据节点状态（目的：关联搜索结构选中状态修改）
        this.$store.dispatch("orgTree/updateFlatTreeData", node);
      }
    },

    toggleAllNodeSelection(item, status = "") {
      return new Promise((resolve) => {
        // 使用 setTimeout 确保异步执行
        setTimeout(() => {
          if (status) {
            item.checkedStatus = status;
          } else {
            item.checkedStatus =
              item.checkedStatus === "checked" ? "unchecked" : "checked";
          }
          this.handleUpdateCheckedNodes(item);

          if (item.children && item.children.length > 0) {
            // 使用 Promise.all 等待所有子节点的处理完成
            Promise.all(
              item.children.map((child) =>
                this.toggleAllNodeSelection(child, item.checkedStatus)
              )
            ).then(() => {
              resolve(item);
            });
          } else {
            resolve(item);
          }
        }, 0);
      });
    },

    getNodeCheckedStatus(item) {
      if (!item.children || item.children.length === 0) {
        return item.checkedStatus;
      }
      let checkCount = 0;
      let uncheckCount = 0;
      item.children.forEach((child) => {
        if (child.checkedStatus === "checked") {
          checkCount++;
        } else if (child.checkedStatus === "unchecked") {
          uncheckCount++;
        }
      });
      if (checkCount === item.children.length) {
        return "checked";
      } else if (uncheckCount === item.children.length) {
        return "unchecked";
      } else {
        return "indeterminate";
      }
    },

    async handleToggleNodeSelection(item, removeTag = false) {
      console.log("toggle node selection", item);

      // 搜索，目前仅成员，修改成员关联上级部门选中状态
      if (this.searchText || removeTag) {
        item.checkedStatus =
          item.checkedStatus === "checked" ? "unchecked" : "checked";
        this.handleUpdateCheckedNodes(item);

        // 收集所有需要更新的节点（包括父链）
        const nodesToUpdate = new Map([[item.id, item]]);
        let current = item;
        while (current.parentId) {
          const p = this.flatTreeData.find((n) => n.id === current.parentId);
          if (!p) break;

          p.children = p.children.map((child) => {
            if (child.id === current.id) {
              child = current;
            }
            return child;
          });

          p.checkedStatus = this.getNodeCheckedStatus(p);

          nodesToUpdate.set(p.id, p);
          current = p;
        }

        const updates = Array.from(nodesToUpdate.values()).reverse();
        this.$store.dispatch("orgTree/updateFlatTreeDataBatch", updates);

        console.log("链路节点列表===", updates);
        console.log(
          "链路节点列表Id",
          updates.map((cur) => cur.id)
        );
        console.log(
          "链路节点列表Label",
          updates.map((cur) => cur.label)
        );
        console.log(
          "链路节点列表选中状态",
          updates.map((cur) => cur.checkedStatus)
        );

        const rootNode = this.flatTreeData.find((n) => n.id === updates[0].id);
        console.log("根节点", rootNode);

        this.$store.dispatch("orgTree/updateNodeRecursive", rootNode);
        console.log("修改后orginTreeData", this.orginTreeData);

        return;
      }

      this.isConfirming = true;

      if (
        item.checkedStatus === "unchecked" ||
        item.checkedStatus === "indeterminate"
      ) {
        await this.toggleAllNodeSelection(item, "checked");
      } else {
        await this.toggleAllNodeSelection(item);
      }
      this.isConfirming = false;

      const index = this.localOrgList.findIndex((cur) => cur.id === item.id);
      this.localOrgList[index] = item;
      this.$emit("change", this.localOrgList);
    },

    async handleAllNodeSelection() {
      let status = "checked";
      if (this.isAllChecked) {
        status = "unchecked";
      }

      this.isConfirming = true;
      // 使用 Promise.all 并行处理所有项
      await Promise.all(
        this.localOrgList.map(async (item) => {
          await this.toggleAllNodeSelection(item, status);
          return item;
        })
      );
      this.isConfirming = false;

      // 由于 toggleAllNodeSelection 会直接修改 item，我们可以直接使用原数组
      this.$emit("change", this.localOrgList);
    },

    handleChildrenChange(newChildData) {
      this.currentChildren = newChildData;
      if (newChildData && newChildData.length > 0) {
        let checkCount = 0;
        let uncheckCount = 0;
        newChildData.forEach((item) => {
          if (item.checkedStatus === "checked") {
            checkCount++;
          } else if (item.checkedStatus === "unchecked") {
            uncheckCount++;
          }
        });

        let parentStatus = "unchecked";
        if (checkCount === newChildData.length) {
          parentStatus = "checked";
        } else if (uncheckCount === newChildData.length) {
          parentStatus = "unchecked";
        } else {
          parentStatus = "indeterminate";
        }

        const parentId = newChildData[0].parentId;
        const index = this.localOrgList.findIndex((cur) => cur.id === parentId);
        this.localOrgList[index].children = newChildData;
        this.localOrgList[index].checkedStatus = parentStatus;

        this.$emit("change", this.localOrgList);
      }
    },

    scrollToRight() {
      this.$nextTick(() => {
        const wrapper = this.$el.querySelector(".selected-items-wrapper");
        if (wrapper) {
          wrapper.scrollLeft = wrapper.scrollWidth;
        }
      });
    },

    handleConfirm() {
      this.isConfirming = true;

      // 模拟异步操作
      setTimeout(() => {
        console.log("确认选择", this.checkedNodes);
        this.$emit("confirm", this.checkedNodes);
        this.isConfirming = false;
      }, 1000);
    },
  },
};
</script>

<style scoped lang="less">
.org-container {
  position: relative; // 为绝对定位的加载层提供参照
  display: flex;
  flex-direction: column;
  height: 100%;
  background: #f5f5f5;
}

.global-loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100; // 确保在最上层
}

.nav-bar {
  height: 46px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 15px;
  background: #fff;
  // box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  z-index: 2;

  .nav-left {
    display: flex;
    align-items: center;

    .back-icon {
      margin-right: 10px;
      color: #1989fa;
    }
  }

  .all-selection {
    color: #1989fa;
    font-size: 14px;
  }
}

.search-bar {
  padding: 10px;
  background: #fff;
  position: sticky;
  top: 46px;
  z-index: 1;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1); /* 新增底部阴影 */

  .van-search {
    padding: 0;
    box-shadow: none; /* 确保内部搜索框不重复阴影 */
  }
}

.scroll-content {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.selection-bar {
  padding: 10px 15px;
  background: #fff;
  border-top: 1px solid #eee;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);

  height: 90px; /* 改为固定值更稳定 */
  display: flex;
  flex-direction: column;
  .selected-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    flex-shrink: 0; /* 防止被压缩 */

    span {
      font-size: 14px;
      color: #1989fa;
    }

    .van-button {
      height: 24px;
      line-height: 22px;
      padding: 0 8px;
    }
  }
  .selected-items-wrapper {
    /* 核心修正 */
    flex: 1; /* 占满剩余空间 */
    min-height: 0; /* 允许压缩（关键修复）*/

    scroll-behavior: smooth; /* 添加平滑滚动效果 */

    /* 滚动相关 */
    overflow-x: auto;
    overflow-y: hidden;
    white-space: nowrap;

    /* 视觉优化 */
    padding-bottom: 10px;
    margin-top: 5px;

    /* 隐藏滚动条（可选） */
    scrollbar-width: none; /* Firefox */
    &::-webkit-scrollbar {
      display: none; /* Chrome/Safari */
    }
  }

  .selected-items {
    display: inline-block; /* 比inline-flex更稳定 */
    height: 100%; /* 继承父级高度 */

    /* 标签间距控制 */
    .van-tag {
      flex-shrink: 0; /* 禁止标签收缩 */
      margin-right: 8px;
      vertical-align: middle; /* 垂直居中 */
      &:last-child {
        margin-right: 0;
      }
    }
  }
}

.confirm-button-container {
  padding: 10px;
  background: #fff;
  position: sticky;
  bottom: 0;
  z-index: 10;
  box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);

  .van-button {
    height: 44px;
    border-radius: 4px;
  }
}

.row {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  background: #fff;
  border-radius: 8px;
  padding: 0 15px;

  &-department,
  &-member {
    width: 100%;
    display: flex;
    align-items: center;
  }

  .selection-container {
    margin-right: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .content {
    flex: 1;
    display: flex;
    align-items: center;
  }

  .name {
    margin-left: 10px;
  }

  .arrow-icon {
    padding: 8px;
  }
}

.selection-checkbox {
  width: 18px;
  height: 18px;
  border: 1px solid #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s;

  .icon {
    font-size: 12px;
    color: white;
  }

  &.checked {
    background-color: #1989fa;
    border-color: #1989fa;
  }

  &.indeterminate {
    background-color: #1989fa;
    border-color: #1989fa;
  }

  &.department-checkbox {
    border-radius: 4px;

    &.indeterminate .icon {
      font-weight: bold;
    }
  }
}

.child-view {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}
.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.3s ease;
}
.slide-left-enter-from {
  transform: translateX(100%);
}
.slide-left-leave-to {
  transform: translateX(100%);
}
</style>
